package com.allen.dao;

import com.allen.bean.User;
import com.allen.utils.HibernateUtils;
import com.opensymphony.xwork2.ActionContext;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;

import java.util.List;

public class UserDao {

    public boolean login(String username, String password) {
        Session session = HibernateUtils.getSession();
        Query query = session.createQuery("from User where username=? and password=?");
        List<User> list = query.setParameter(0, username).setParameter(1, password).list();
        HibernateUtils.closeSession(session);
        if (list!=null && list.size()>0){
        User user = list.get(0);
            ActionContext.getContext().getSession().put("user", user);
            return true;
        }else {
            return false;
        }
    }

    public List<User> list() {
        Session session = HibernateUtils.getSession();
        List<User> users = session.createQuery("from User").list();
        HibernateUtils.closeSession(session);
        return users;
    }

    public User findById(Integer id) {
        Session session = HibernateUtils.getSession();
        //User user = (User)session.createQuery("from User where id=?").setParameter(0,id).uniqueResult();
        User user = session.get(User.class, id);
        HibernateUtils.closeSession(session);
        return user;
    }

    public void update(User user) {
        Session session = HibernateUtils.getSession();
        Transaction transaction = session.beginTransaction();
        session.update(user);
        transaction.commit();
        HibernateUtils.closeSession(session);
    }

    public void delete(Integer id) {
        Session session = HibernateUtils.getSession();
        Transaction transaction = session.beginTransaction();
        User user = session.get(User.class, id);
        session.delete(user);
        transaction.commit();
        HibernateUtils.closeSession(session);
    }

    public void add(User user) {
        Session session = HibernateUtils.getSession();
        Transaction transaction = session.beginTransaction();
        session.save(user);
        transaction.commit();
        HibernateUtils.closeSession(session);
    }

    public List<User> find(String username) {
        Session session = HibernateUtils.getSession();
        Query query = session.createQuery("from User where username like ?");
        List<User> users = query.setParameter(0, "%" + username + "%").list();
        return users;
    }
}
